package entity

import (
	"time"
	"xr-game-server/core/constants/common"
	"xr-game-server/core/constants/db"
	"xr-game-server/core/math"
	"xr-game-server/core/migrate"
	"xr-game-server/core/snowflake"
	"xr-game-server/core/syndb"
)

const (
	// TbPlayerRes 表名
	TbPlayerRes db.TbName = "player_res"
)

// 列名
const (
	PlayerResRoleId db.TbCol = "role_id"
	PlayerResVal    db.TbCol = "val"
	PlayerResTypeId db.TbCol = "type_id"
)

// PlayerRes 玩家角色
type PlayerRes struct {
	migrate.OneModel
	RoleId uint64 `gorm:"default:0;comment:角色id"`
	Val    uint64 `gorm:"default:0;comment:数值"`
	TypeId uint64 `gorm:"default:0;comment:类型id"`
}

func NewPlayerRes(roleId uint64, typeId uint64) *PlayerRes {
	ret := &PlayerRes{}

	ret.ID = snowflake.GetId()
	ret.SetRoleId(roleId)
	ret.SetTypeId(typeId)

	ret.SetCreatedAt(time.Now())
	ret.SetUpdatedAt(time.Now())
	return ret
}

func (this *PlayerRes) Add(val uint64) {
	this.Val += math.ChkUInt64(this.Val, val)
	this.SetVal(this.Val)
}
func (this *PlayerRes) Consume(val uint64) {
	if val >= this.Val {
		this.Val = common.Zero
	} else {
		this.Val -= val
	}
	this.SetVal(this.Val)
}

func (receiver *PlayerRes) SetRoleId(roleId uint64) {
	receiver.RoleId = roleId
	syndb.AddDataToLazyChan(TbPlayerRes, PlayerResRoleId, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: roleId,
	})
}

func (receiver *PlayerRes) SetVal(val uint64) {
	receiver.Val = val
	receiver.SetUpdatedAt(time.Now())
	syndb.AddDataToLazyChan(TbPlayerRes, PlayerResVal, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: val,
	})
}

func (receiver *PlayerRes) SetTypeId(typeId uint64) {
	receiver.TypeId = typeId
	syndb.AddDataToLazyChan(TbPlayerRes, PlayerResTypeId, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: typeId,
	})
}

func (receiver *PlayerRes) SetCreatedAt(val time.Time) {
	receiver.CreatedAt = val
	syndb.AddDataToLazyChan(TbPlayerRes, db.CreatedAtName, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: val,
	})
}

func (receiver *PlayerRes) SetUpdatedAt(val time.Time) {
	receiver.UpdatedAt = val
	syndb.AddDataToLazyChan(TbPlayerRes, db.UpdatedAtName, &syndb.ColData{
		IdVal:  receiver.ID,
		ColVal: val,
	})
}

func initPlayerRes() {
	syndb.RegLazyWithSmall(TbPlayerRes, db.CreatedAtName)
	syndb.RegLazyWithSmall(TbPlayerRes, db.UpdatedAtName)

	syndb.RegLazyWithSmall(TbPlayerRes, PlayerResVal)
	syndb.RegLazyWithSmall(TbPlayerRes, PlayerResRoleId)
	syndb.RegLazyWithSmall(TbPlayerRes, PlayerResTypeId)

	migrate.AutoMigrate(&PlayerRes{})
}
